package com.lw.leetcode.back.b;

/**
 * 130. 被围绕的区域
 *
 * @Author liw
 * @Date 2021/4/29 11:43
 * @Version 1.0
 */
public class Solve {

    public void solve(char[][] board) {
        int m = board.length;
        int n = board[0].length;
        for (int i = 0; i < m; i++) {
            find(board, i, 0);
            find(board, i, n - 1);
        }
        for (int i = 0; i < n; i++) {
            find(board, 0, i);
            find(board, m - 1, i);

        }
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                char value = board[i][j];
                if (value == 'O') {
                    board[i][j] = 'X';
                } else if (value == '1') {
                    board[i][j] = 'O';
                }
            }
        }
    }

    private void find(char[][] board, int i, int j) {
        int m = board.length;
        int n = board[0].length;
        if (i < 0 || i >= m) {
            return;
        }
        if (j < 0 || j >= n) {
            return;
        }
        char value = board[i][j];
        if (value != 'O') {
            return;
        }
        board[i][j] = '1';
        find(board, i + 1, j);
        find(board, i - 1, j);
        find(board, i, j + 1);
        find(board, i, j - 1);
    }

}
